import type { ConfigProviderThemeVars } from 'vant';
import type { DeckItem, DeckList } from '/@/api/currentDeck/model/deckModel';
import { defineComponent, reactive, ref, unref } from 'vue';
import { appShareUsing, getAppParameters } from '/@/utils/appInteractive';
import { useGo } from '/@/hooks/web/usePage';
import { useUserStore } from '/@/store/modules/user';
import { useCurrentDeckStore } from '/@/store/modules/currentDeck';
import { useMessage } from '/@/hooks/web/useMessage';
import { aTabClick, awaitWrap } from '/@/utils';
import { formatToDateTime } from '/@/utils/dateUtil';
import { useCurrentDeckConfigHooks } from '/@/views/currentDeck/hooks/useConfigs';
import { remove } from 'lodash-es';
import { Button, Checkbox, ConfigProvider, Empty } from 'vant';
import { Icon } from '/@/components/Icon';
import Title from '/@/views/general/components/Title';
import { DeckListApi, DeleteDeckApi } from '/@/api/currentDeck/deck';

import('./index.less');

export default defineComponent({
  name: 'CurrentDeckListPage',
  props: {
    gameId: {
      type: String as PropType<string>,
      required: true,
    },
  },
  setup(props) {
    const { deckConfigData } = useCurrentDeckConfigHooks({ game_id: props.gameId });
    // 设置分享参数
    getAppParameters(); // 需要重新获取一下token 因为是在app使用
    appShareUsing({} as any);

    const { createSuccessToast } = useMessage();

    const go = useGo();
    const userStore = useUserStore();
    const currentStore = useCurrentDeckStore();
    currentStore.setGameId(props.gameId);

    const switchState = ref(false); // 是否出现删除按钮
    const selectedAll = ref(false); // 是否全选
    const selectedDeckIds = ref<number[]>([]);

    const SwitchButton = () => {
      if (!userStore.getToken) {
        return null;
      }
      const themeVars: ConfigProviderThemeVars = {
        buttonBorderWidth: '0',
        buttonDefaultBackground: 'none',
      };

      if (unref(switchState)) {
        return (
          <ConfigProvider
            themeVars={{
              ...themeVars,
              buttonDefaultColor: '#1380F0',
            }}
          >
            <Button
              size={'small'}
              icon={'success'}
              onClick={() => {
                switchState.value = false;
              }}
            >
              完成
            </Button>
          </ConfigProvider>
        );
      }
      return (
        <ConfigProvider themeVars={themeVars}>
          <Button
            size={'small'}
            icon={'bars'}
            iconPosition={'right'}
            onClick={() => {
              switchState.value = true;
              selectedAll.value = false;
              deckList.rows.map((item) => {
                item.isCheck = false;
              });
              selectedDeckIds.value = [];
            }}
          >
            编辑
          </Button>
        </ConfigProvider>
      );
    };

    const BottomBox = () => {
      const selectAllClick = (val: boolean) => {
        deckList.rows.map((item) => {
          item.isCheck = val;
        });
      };
      const token = userStore.getToken;
      let actionHtml: VueNode = null;
      const themeVars: ConfigProviderThemeVars = {
        buttonBorderWidth: '0',
        buttonDefaultBackground: 'none',
        buttonDefaultColor: '#1380F0',
      };
      if (!token) {
        // aTabClick('wanxiu://innerlink?type=weblogin');
      }
      actionHtml = (
        <a class={'block'}>
          <ConfigProvider themeVars={themeVars}>
            <Button
              icon={'plus'}
              size={'large'}
              onClick={() => {
                if (!token) {
                  aTabClick('wanxiu://innerlink?type=weblogin');
                  return false;
                }
                // gaterulerStore.clearCreateDeckParams();
                go('/currentdeckcreate', true);
              }}
            >
              创建套牌
            </Button>
          </ConfigProvider>
        </a>
      );
      if (unref(switchState)) {
        actionHtml = (
          <ConfigProvider
            themeVars={{
              checkboxLabelColor: '#1380F0',
            }}
            class={'delete-box flex items-center h-full justify-between'}
          >
            <Checkbox v-model={[selectedAll.value]} onChange={selectAllClick}>
              全选
            </Checkbox>
            <Button size={'small'} type={'primary'} disabled={!unref(selectedDeckIds).length} onClick={deleteDeck}>
              删除
            </Button>
          </ConfigProvider>
        );
      }
      return <div class={'bottom-action-box'}>{actionHtml}</div>;
    };

    const DeckListBox = () => {
      const listItemHtml: VueNode[] = [];
      const deckItemChange = (val: boolean, deck: DeckItem) => {
        if (val) {
          unref(selectedDeckIds).push(deck.deck_id);
        } else {
          const index = unref(selectedDeckIds).indexOf(deck.deck_id);
          unref(selectedDeckIds).splice(index, 1);
        }
      };
      for (let i = 0; i < deckList.rows.length; i++) {
        const item = deckList.rows[i];
        listItemHtml.push(
          <li class={unref(switchState) ? 'deck-list-item selected' : 'deck-list-item'}>
            {unref(switchState) ? (
              <div class={'checks'}>
                <Checkbox
                  v-model={[item.isCheck]}
                  onChange={(val) => {
                    deckItemChange(val, item);
                  }}
                />
              </div>
            ) : null}
            <div
              onClick={() => {
                go(`/currentdeckdetail/${item.deck_id}`);
              }}
            >
              <div class={'item-title flex justify-between'}>
                <span class={'van-ellipsis w-[60%]'}>{item.deck_name}</span>
                {deckConfigData.has_price ? (
                  <span>{item.price ? `预估: ${item.price / 100}元` : '暂无售价'}</span>
                ) : null}
              </div>
              <div class={'flex justify-between text-sm mt-md'}>
                <span class={'text-gray-400'}>{formatToDateTime(item.updated_at, 'YYYY-MM-DD')}</span>
                <div class={'flex items-center'}>
                  <Icon icon={item.is_open ? 'mdi:eye-outline' : 'mdi:eye-off-outline'} />
                  <span class={'ml-lg'}>{item.card_number}张</span>
                </div>
              </div>
            </div>
          </li>
        );
      }
      return <ul class={'deck-list-box'}>{listItemHtml}</ul>;
    };

    const deckList = reactive<DeckList>({
      total: 0,
      rows: [],
    });
    const getList = async () => {
      const [error, data] = await awaitWrap(DeckListApi({ page: 1, size: 120, game_id: props.gameId }));
      if (error) {
        return;
      }
      const result = data as DeckList;
      deckList.total = result.total;
      deckList.rows = result.rows;
    };
    getList();

    const deleteDeck = async () => {
      const [error] = await awaitWrap(DeleteDeckApi(unref(selectedDeckIds)));
      if (error) {
        return false;
      }
      remove(deckList.rows, (item) => {
        return unref(selectedDeckIds).indexOf(item.deck_id) >= 0;
      });
      selectedDeckIds.value = [];
      createSuccessToast({
        message: '套牌删除成功',
      });
    };

    return () => (
      <div class={'current-deck-list-page'}>
        <Title title={'我的套牌'} />
        <div class={'deck-list-container'}>
          <div class={'switch-box flex justify-between text-sm'}>
            <span>我的套牌</span>
            <SwitchButton />
          </div>
          <BottomBox />
          {deckList.rows.length ? <DeckListBox /> : <Empty description='您暂时没有套牌，快去创建吧' />}
        </div>
      </div>
    );
  },
});
